/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.mock_collaborator_injection;

import picounit.mocker.MockFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class CollaboratorsInvocationHandler implements InvocationHandler {
	private final MockFactory mockFactory;
	private final Map<String, Object> mockMap = new HashMap<String, Object>();

	public CollaboratorsInvocationHandler(MockFactory mockFactory) {
		this.mockFactory = mockFactory;
	}

	// TODO: How can I deal with the 'Collaborators' interface returning a generic type,
	//       I will need to pay attention to the CheckCastRegistry
	// TODO: Allow the use of abstract classes
	public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {
		Object mock = mockMap.get(method.getName());

		if (mock == null) {
			mock = mockFactory.mock(method.getReturnType(), method.getName());

			mockMap.put(method.getName(), mock);
		}

		return mock;
	}

	public void clearMap() {
		mockMap.clear();
	}
}
